package ahblue.cn.tanzi.ui.home;

import android.content.Context;
import android.content.Intent;
import android.opengl.Visibility;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import ahblue.cn.tanzi.R;
import ahblue.cn.tanzi.data.HomeArticle;
import ahblue.cn.tanzi.data.source.ApiCallback;
import ahblue.cn.tanzi.data.source.RemoteRepository;
import ahblue.cn.tanzi.model.home.BannerAd;
import ahblue.cn.tanzi.model.home.HomeModel;
import ahblue.cn.tanzi.model.home.VideoDetailModel;
import ahblue.cn.tanzi.model.user.LoginResultModel;
import ahblue.cn.tanzi.model.user.UserModel;
import ahblue.cn.tanzi.ui.home.article.ArticleDetailActivity;
import ahblue.cn.tanzi.ui.home.article.HomeArticleActivity;
import ahblue.cn.tanzi.ui.home.search.SearchActivity;
import ahblue.cn.tanzi.ui.home.video.VideoDetailActivity;
import ahblue.cn.tanzi.util.GlideApp;
import ahblue.cn.tanzi.util.SharePreferenceUtil;
import ahblue.cn.tanzi.util.TimeUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static ahblue.cn.tanzi.ui.home.HomeFragment.MultipleItem.TYPE_MODEL;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment {

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.btn_history)
    ImageButton mRightButton;

    private MultipleItemQuickAdapter mAdapter;
    private final List<MultipleItem> mItemList = new ArrayList<>();

    private final static int ARG_PAGE_COUNT = 5;
    private int mPage = 0;

    private boolean mIsRefresh;
    private boolean mIsLoadMore;
    private SharePreferenceUtil sharePreferenceUtil;

    @OnClick(R.id.layout_search)
    void onClickSearch() {
        final Intent intent = new Intent(getActivity(), SearchActivity.class);
        startActivity(intent);
    }

    public HomeFragment() {
        mItemList.add(new MultipleItem(MultipleItem.TYPE_BANNER));
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        sharePreferenceUtil = new SharePreferenceUtil(getActivity().getApplicationContext());
        mAdapter = new MultipleItemQuickAdapter(mItemList);
        mAdapter.setOnItemClickListener(mOnItemClickListener);
        mRecyclerView.setAdapter(mAdapter);
        mRightButton.setVisibility(View.INVISIBLE);
        final GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return mAdapter.getItemViewType(position) == TYPE_MODEL ? 1 : manager.getSpanCount();
            }
        });
        mRecyclerView.setLayoutManager(manager);

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPage = 0;

                Iterator<MultipleItem> iter = mItemList.iterator();
                while (iter.hasNext()) {
                    MultipleItem item = iter.next();
                    if (item.getItemType() == MultipleItem.TYPE_ARTICLE) {
                        iter.remove();
                    }
                }
                mIsRefresh = true;
                loadArticles4Page(0);
            }
        });
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mPage += 1;
                mIsLoadMore = true;
                loadArticles4Page(mPage);
            }
        });


        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initData();
    }

    private void initData() {
        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.getBigShotIndexTop(mBannerCallback);
        repo.getBigShotIndexCategory(mHomeModelCallback);

        loadArticles4Page(mPage);
        isVip();
    }

    /**
     * 加载指定页面的文章列表
     *
     * @param page 页码
     */
    private void loadArticles4Page(int page) {
        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.getBigShotIndexList(page, ARG_PAGE_COUNT, mArticleCallback);
    }

    /**
     * 广告条回调接口
     */
    ApiCallback<List<BannerAd>> mBannerCallback = new ApiCallback<List<BannerAd>>() {
        @Override
        public void onSuccess(List<BannerAd> data) {
            mItemList.get(0).setData(data);
            mAdapter.notifyDataSetChanged();
        }

        @Override
        public void onFailed(String errorMsg) {

        }
    };

    /**
     * 首页文章列表接口回调
     */
    ApiCallback<List<HomeArticle>> mArticleCallback = new ApiCallback<List<HomeArticle>>() {
        @Override
        public void onSuccess(List<HomeArticle> data) {
            List<MultipleItem> topData = new ArrayList<>();
            List<MultipleItem> otherData = new ArrayList<>();
            for (HomeArticle article : data) {
                MultipleItem item = new MultipleItem(MultipleItem.TYPE_ARTICLE);
                item.setData(article);
                if ("1".equals(article.is_top)){
                    topData.add(item);
                }else {
                    otherData.add(item);
                }

            }
            mItemList.addAll(topData);
            mItemList.addAll(otherData);

            mAdapter.notifyDataSetChanged();

            if (mIsRefresh) {
                mIsRefresh = false;
                mRefreshLayout.finishRefresh(true);
            }

            if (mIsLoadMore) {
                mIsLoadMore = false;
                mRefreshLayout.finishLoadmore(true);
            }
        }

        @Override
        public void onFailed(String errorMsg) {
            if (mIsRefresh) {
                mIsRefresh = false;
                mRefreshLayout.finishRefresh(false);
            }

            if (mIsLoadMore) {
                mIsLoadMore = false;
                mRefreshLayout.finishLoadmore(false);
            }
        }
    };

    /**
     * 首页第一级菜单
     */
    ApiCallback<List<HomeModel>> mHomeModelCallback = new ApiCallback<List<HomeModel>>() {
        @Override
        public void onSuccess(List<HomeModel> data) {
            addModel(data);
        }

        @Override
        public void onFailed(String errorMsg) {
            // 出错添加默认
            addModel(null);
        }
    };

    /**
     * 添加首页以及菜单
     */
    private void addModel(List<HomeModel> data) {
        Iterator<MultipleItem> iter = mItemList.iterator();
        while (iter.hasNext()) {
            MultipleItem item = iter.next();
            if (item.getItemType() == MultipleItem.TYPE_MODEL) {
                iter.remove();
            }
        }
        if (data == null || data.isEmpty()) {
            data = HomeModel.createDefaultModel();
        }
        int insertIndex = 1;
        for (HomeModel model : data) {
            MultipleItem item = new MultipleItem(MultipleItem.TYPE_MODEL);
            item.setData(model);
            mItemList.add(insertIndex, item);
            insertIndex++;
        }
        mAdapter.notifyDataSetChanged();
    }

    private void goArticles(int type, String typeName) {
        final Intent intent = new Intent(getActivity(), HomeArticleActivity.class);
        intent.putExtra("ArticleType", type);
        intent.putExtra("ArticleTypeName", typeName);
        startActivity(intent);
    }

    BaseQuickAdapter.OnItemClickListener mOnItemClickListener = new BaseQuickAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            MultipleItem item = mItemList.get(position);
            if (item.getItemType() == MultipleItem.TYPE_ARTICLE) {
                HomeArticle article = (HomeArticle) item.getData();
                if (article.type == 1){
                    final Intent intent = new Intent(HomeFragment.this.getContext(), ArticleDetailActivity.class);
                    intent.putExtra(ArticleDetailActivity.ARG_ARTICLE_ID, article.id);
                    intent.putExtra(ArticleDetailActivity.ARG_ARTICLE_TITLE, article.title);
                    startActivity(intent);
                }else if (article.type == 2){
                    Intent intent = new Intent(HomeFragment.this.getContext(), VideoDetailActivity.class);
                    intent.putExtra("id", article.id + "");
                    startActivity(intent);
                }

            } else if  (item.getItemType() == MultipleItem.TYPE_MODEL) {
                HomeModel model = (HomeModel) item.getData();
                goArticles(model.id, model.category_title);
            }
        }
    };

    class MultipleItem implements MultiItemEntity {

        static final int TYPE_BANNER = 1;
        static final int TYPE_MODEL = 2;
        static final int TYPE_ARTICLE = 3;
        static final int TYPE_MENU = 4;

        private int mItemType;
        private Object mData;

        MultipleItem(int type) {
            mItemType = type;
        }

        @Override
        public int getItemType() {
            return mItemType;
        }

        public void setData(Object data) {
            mData = data;
        }

        public Object getData() {
            return mData;
        }
    }

    class MultipleItemQuickAdapter extends BaseMultiItemQuickAdapter<MultipleItem, BaseViewHolder> {

        /**
         * Same as QuickAdapter#QuickAdapter(Context,int) but with
         * some initialization data.
         *
         * @param data A new list is created out of this one to avoid mutable list
         */
        MultipleItemQuickAdapter(List<MultipleItem> data) {
            super(data);

            addItemType(MultipleItem.TYPE_BANNER, R.layout.item_home_ad_bar);
            addItemType(MultipleItem.TYPE_MODEL, R.layout.item_home_model);
            addItemType(MultipleItem.TYPE_MENU, R.layout.item_home_menu_bar);
            addItemType(MultipleItem.TYPE_ARTICLE, R.layout.item_home_article);
        }

        @Override
        protected void convert(BaseViewHolder helper, MultipleItem item) {
            switch (helper.getItemViewType()) {
                case MultipleItem.TYPE_BANNER:
                    convertAdBanner(helper, item);
                    break;
                case MultipleItem.TYPE_MODEL:
                    convertModel(helper, item);
                    break;
                case MultipleItem.TYPE_MENU:
                    convertMenuBar(helper, item);
                    break;
                case MultipleItem.TYPE_ARTICLE:
                    convertArticle(helper, item);
                    break;
                default:
                    break;
            }
        }

        private void convertArticle(BaseViewHolder helper, MultipleItem multipleItem) {
            HomeArticle item = (HomeArticle) multipleItem.getData();
            ImageView iv = helper.getView(R.id.iv_news_cover);
            GlideApp.with(iv).load(item.image).into(iv);

            helper.setText(R.id.tv_news_title, item.title);
            helper.setText(R.id.tv_news_author, item.member_name);

            if (item.type == 2){
                helper.setVisible(R.id.iv_cover_player,true);
            }else {
                helper.setVisible(R.id.iv_cover_player,false);
            }
            String strTime = TimeUtils.getStandardDate(item.add_time);
            helper.setText(R.id.tv_news_time, strTime);
            helper.setText(R.id.tv_read_count, "阅读 " + Integer.toString(item.read_count));
            if ("1".equals(item.is_top)){
                helper.getView(R.id.tv_top).setVisibility(View.VISIBLE);
            }else {
                helper.getView(R.id.tv_top).setVisibility(View.GONE);
            }

        }

        private void convertMenuBar(BaseViewHolder helper, MultipleItem item) {
            helper.addOnClickListener(R.id.linerlayout_yin_liu_ji_shu);
            helper.addOnClickListener(R.id.linerlayout_ruan_jian_kai_fa);
            helper.addOnClickListener(R.id.linerlayout_dai_kuan_kou_zi);
            helper.addOnClickListener(R.id.linerlayout_zhi_xiao_ban_kuai);
            helper.addOnClickListener(R.id.linerlayout_wang_zhuan);
            helper.addOnClickListener(R.id.linerlayout_qu_kuai_lian);
        }

        private void convertModel(BaseViewHolder helper, MultipleItem multipleItem) {
            HomeModel model = (HomeModel) multipleItem.getData();
            helper.setText(R.id.tv_home_model, model.category_title);
            helper.setImageResource(R.id.iv_home_model, model.getIconResId());
        }

        private void convertAdBanner(BaseViewHolder helper, MultipleItem item) {
            List<BannerAd> data = (List<BannerAd>) item.getData();
            if (data == null || data.size() == 0) {
                return;
            }

            List<String> images = new ArrayList<>();
            for (BannerAd bannerAd : data) {
                images.add(bannerAd.image);
            }

            Banner banner = helper.getView(R.id.banner);
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    if (data != null && data.size() > position && data.get(position) != null){

                        Intent intent = new Intent(HomeFragment.this.getContext(), ArticleDetailActivity.class);
                        intent.putExtra(ArticleDetailActivity.ARG_ARTICLE_ID, data.get(position).id);
                        intent.putExtra(ArticleDetailActivity.ARG_ARTICLE_TITLE, data.get(position).title);
                        startActivity(intent);
                    }else {
                        Toast.makeText(HomeFragment.this.getContext(), "广告条接口数据未提供", Toast.LENGTH_LONG)
                                .show();
                    }
                }
            });
            banner.setImageLoader(
                    new ImageLoader() {
                        @Override
                        public void displayImage(Context context, Object id, ImageView imageView) {
                            GlideApp.with(context).load(id).into(imageView);
                        }
                    })
                    .setImages(images)
                    .setBannerAnimation(Transformer.Default)
                    .isAutoPlay(true)
                    .setDelayTime(2500)
                    .setIndicatorGravity(BannerConfig.CENTER)
                    .start();

        }
    }

    /**
     * 判断用是否是充值会员，如果不是就结束界面
     */
    private void isVip() {
        UserModel.getUserInfo(getActivity(), LoginResultModel.getToken(getActivity()), new UserModel.UserInfoLoginStatus() {
            @Override
            public void conver(UserModel m) {

                //获取过期时间
                if (m != null){
                    String expiredTime  = m.expired_time;
                    sharePreferenceUtil.setExpiredTime(expiredTime);
                }


            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isHidden()){
            isVip();
        }
    }
}
